package com.metaera.app.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.lxj.xpopup.XPopup;
import com.metaera.app.Constants;
import com.metaera.app.R;
import com.metaera.app.controller.presenter.ArticleDetailsPresenter;
import com.metaera.app.controller.presenter.ArticleRecommendPresenter;
import com.metaera.app.controller.presenter.LikeInformationPresenter;
import com.metaera.app.controller.view.BasicNetworkRequestView;
import com.metaera.app.data.model.ArticleListResponse;
import com.metaera.app.data.model.InformationDetailsResponse;
import com.metaera.app.data.network.ApiParam;
import com.metaera.app.ui.adapters.ArticleRecommendAdapter;
import com.metaera.app.ui.core.BaseRequestActivity;
import com.metaera.app.ui.popup.SharePopup;
import com.metaera.app.utils.DateTime;
import com.metaera.app.utils.LoginClickListener;
import com.metaera.app.utils.ShareClickListener;
import com.metaera.app.utils.ViewUtils;
import com.metaera.app.utils.image.GlideApp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.recyclerview.widget.RecyclerView;

/**
 * 快讯详情
 */
public class FlashNewsDetailsActivity extends BaseRequestActivity {

    public static Intent newInstance(Context context, int id) {
        Intent intent = new Intent(context, FlashNewsDetailsActivity.class);
        intent.putExtra(Constants.ARTICLE_ID, id);
        return intent;
    }

    public static Intent newInstance(Context context, int id, String title, String content, int date, int score) {
        Intent intent = new Intent(context, FlashNewsDetailsActivity.class);
        intent.putExtra(Constants.ARTICLE_ID, id);
        intent.putExtra("TITLE", title);
        intent.putExtra("CONTENT", content);
        intent.putExtra("DATE", date);
        intent.putExtra("SCORE", score);
        return intent;
    }


//    private WebView mWebView;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_flash_news_details;
    }

    @Override
    protected void initialize(Bundle savedInstanceState) {
        ViewUtils.addStatusBarHeightPadding(findViewById(R.id.layout_container));

        // find
        RecyclerView recycleRecommend = findViewById(R.id.recycle_recommend);

        // init
        Intent intent = getIntent();
        int articleId = intent.getIntExtra(Constants.ARTICLE_ID, 0);

        String title = intent.getStringExtra("TITLE");
        if (title != null) {
            InformationDetailsResponse bean = new InformationDetailsResponse();
            bean.setTitle(title);
            bean.setContent(intent.getStringExtra("CONTENT"));
            bean.setRelease_time_stamp(intent.getIntExtra("DATE", 0));
            bean.setScore(intent.getIntExtra("SCORE", 0));
            renderArticle(bean);
        }

        // network
        ArticleDetailsPresenter presenter = new ArticleDetailsPresenter();
        presenter.setModelAndView(this::renderArticle);
        presenter.execute(articleId);

        ArticleRecommendPresenter recommendPresenter = new ArticleRecommendPresenter();
        recommendPresenter.setModelAndView(data -> recycleRecommend.setAdapter(new ArticleRecommendAdapter(data)));
        recommendPresenter.execute(articleId);

        // listener
        findViewById(R.id.iv_arrow_back).setOnClickListener(v -> finish());
    }

    private void renderArticle(InformationDetailsResponse data) {
        TextView tvDate = findViewById(R.id.tv_date);
        TextView tvTitle = findViewById(R.id.tv_title);
        RatingBar ratingBar = findViewById(R.id.rating_bar);
        TextView tvDenyNumber = findViewById(R.id.tv_deny_number);
        TextView tvLikeNumber = findViewById(R.id.tv_like_number);

        tvLikeNumber.setText(getString(R.string.item_li_hao) + " " + data.getLike_num());
        tvDenyNumber.setText(getString(R.string.item_li_kong) + " " + data.getDeny_num());
        tvLikeNumber.setSelected(data.getLike_num() > data.getDeny_num());
        tvDenyNumber.setSelected(data.getDeny_num() > data.getLike_num());

        ratingBar.setRating(data.getScore());
        tvTitle.setText(data.getTitle());
        tvDate.setText(DateTime.format(new Date(data.getRelease_time_stamp() * 1000L)));

        TextView tv_content = findViewById(R.id.tv_content);
        tv_content.setText(data.getContent());

        ImageView ivImage = findViewById(R.id.iv_image);
        if (!TextUtils.isEmpty(data.getPic())) {
            ivImage.setVisibility(View.VISIBLE);
            GlideApp.with(this).load(data.getPic()).miniThumb().into(ivImage);
        }

//        String desc = data.getContent();
//        String description = (desc.length() > 25 ? desc.substring(0, 25) : desc) + "...";
//        String description = (getChinese(desc).length() > 25 ? getChinese(desc).substring(0, 25) : desc) + "...";
        String description = data.getIllustrate();

        findViewById(R.id.iv_share).setOnClickListener(v -> new XPopup.Builder(v.getContext())
                .asCustom(
                        new SharePopup(
                                v.getContext(),
                                data.getTitle(),
                                description,
                                ApiParam.LINK_SHARE_9 + data.getId(),
                                R.mipmap.ic_launcher
                        )
                )
                .show());


        findViewById(R.id.tv_wx).setOnClickListener(new ShareClickListener(
                SendMessageToWX.Req.WXSceneSession,
                data.getTitle(),
                description,
                ApiParam.LINK_SHARE_5 + data.getId(),
                R.mipmap.ic_launcher
        ));

        findViewById(R.id.tv_friend).setOnClickListener(new ShareClickListener(
                SendMessageToWX.Req.WXSceneTimeline,
                data.getTitle(),
                description,
                ApiParam.LINK_SHARE_5 + data.getId(),
                R.mipmap.ic_launcher
        ));

        tvLikeNumber.setOnClickListener(new LoginClickListener(v -> {

            LikeInformationPresenter presenter = new LikeInformationPresenter();

            presenter.setModelAndView(new BasicNetworkRequestView<>(o -> {
                data.setIs_like(data.getIs_like() == 1 ? 0 : 1); // 更新是否利好状态
                data.setLike_num(data.getLike_num() + data.getIs_like() == 1 ? 1 : -1); // 增加利好数量
                data.setDeny_num(data.getDeny_num() - 1); // 增少利空数量

                tvLikeNumber.setText(getString(R.string.item_li_hao) + " " + data.getLike_num());
                tvDenyNumber.setText(getString(R.string.item_li_kong) + " " + data.getDeny_num());
                tvLikeNumber.setSelected(data.getLike_num() > data.getDeny_num());
                tvDenyNumber.setSelected(data.getDeny_num() > data.getLike_num());

            }));

            presenter.like(data.getId(), data.getIs_like() == 0);
        }));

        tvDenyNumber.setOnClickListener(new LoginClickListener(v -> {

            LikeInformationPresenter presenter = new LikeInformationPresenter();

            presenter.setModelAndView(new BasicNetworkRequestView<>(o -> {
                data.setIs_deny(data.getIs_deny() == 0 ? 1 : 0); // 更新是否利好状态
                data.setDeny_num(data.getDeny_num() + data.getIs_deny() == 1 ? 1 : -1);
                data.setLike_num(data.getLike_num() - 1); // 增少利空数量

                tvLikeNumber.setText(getString(R.string.item_li_hao) + " " + data.getLike_num());
                tvDenyNumber.setText(getString(R.string.item_li_kong) + " " + data.getDeny_num());
                tvLikeNumber.setSelected(data.getLike_num() > data.getDeny_num());
                tvDenyNumber.setSelected(data.getDeny_num() > data.getLike_num());

            }));

            presenter.deny(data.getId(), data.getIs_deny() == 0);
        }));
    }


//    public String getChinese(String paramValue) {
//        String regex = "([\u4e00-\u9fa5]+)";
//        StringBuilder str = new StringBuilder();
//        Matcher matcher = Pattern.compile(regex).matcher(paramValue);
//        while (matcher.find()) {
//            str.append(matcher.group(0));
//        }
//        return str.toString();
//    }

}
